import { constantRoutes } from '@/router';
import Api from '@/api/permissionApi';
import { Message } from 'element-ui';
import { getUserInfo } from '@/utils/auth';
import Layout from '@/layout';

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

/** 
 * 
 * 判断顶级路由重定向的路由(routerList组装完路由列表)
 * @param routerList
 * 
 *  **/
export function redirectRoute(routerList) {
  return new Promise((resolve, reject) => {
    routerList.forEach(Fitem => {
      if (Fitem.children) {
        for (let i = 0; i < Fitem.children.length; i++) {
          if (!Fitem.children[i].hidden) {
            Fitem.redirect = Fitem.path + '/' + Fitem.children[i].path;
            break;
          }
        }
      }
    })
    resolve(routerList)
  })
}


/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  let keepAlive_arr = ['/client/clientList', '/client/clientSeas', '/project/projectManagement', '/supplier/supplierManagement'];
  data.forEach(item => {
    let menu = {}
    if (item.nodes) {
      menu = {
        path: item.vue_path,
        // name: item.name,
        component: item.vue_component == 'Layout' ? Layout : (resolve) => require([`@/views${item.vue_component}`], resolve),
        hidden: item.vue_hidden == 1 ? false : true,//router菜单显示
        children: [],
        meta: { title: item.name, icon: item.icon, keepAlive: keepAlive_arr.indexOf(item.vue_path) != -1 }
      }
      generaMenu(menu.children, item.nodes)
    } else {
      menu = {
        path: item.vue_path,
        name: item.vue_path,
        component: item.vue_component == 'Layout' ? Layout : (resolve) => require([`@/views${item.vue_component}`], resolve),
        hidden: item.vue_hidden == 1 ? false : true,//router菜单显示
        meta: { title: item.name, icon: item.icon, keepAlive: keepAlive_arr.indexOf(item.vue_path) != -1 }
      }
    }

    routes.push(menu)
  })
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const loadMenuData = []
      const asyncRoutes = []
      Api.getUserMenuList({
        admin_id: getUserInfo().userid
      }).then(res => {
        console.log(res, '权限菜单列表');
        if (res.code == '200') {
          Object.assign(loadMenuData, res.data)
          generaMenu(asyncRoutes, loadMenuData)
        }
        asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
        redirectRoute(asyncRoutes).then(res => {
          commit('SET_ROUTES', res)
          resolve(res)
        })
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
